﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using log4net;

namespace HttpTunnel
{
    public class Listener
    {
        private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static int Port { get; private set; }

        public static void Initialize(Config config)
        {
            Port = config.Port;

            Tunneler.Initialize(config);
        }


        public static void Start()
        {
            try
            {
                var endPoint = new IPEndPoint(IPAddress.Any, Port);
                var listenSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                listenSocket.Bind(endPoint);
                listenSocket.Listen(50);
                listenSocket.BeginAccept(OnAccept, listenSocket);
            }
            catch (Exception ex)
            {
                Logger.Debug("Start", ex);
            }
        }

        private static void OnAccept(IAsyncResult ar)
        {
            var socket = ar.AsyncState as Socket;
            try
            {
                var newSocket = socket.EndAccept(ar);
                Tunneler.StartHandshake(newSocket);
            }
            catch (Exception ex)
            {
                Logger.Debug("OnAccept", ex);
            }

            try
            {
                //Restart Listening
                socket.BeginAccept(OnAccept, socket);
            }
            catch (Exception ex)
            {
                Logger.Debug("OnAccept", ex);
            }
        }

    }
}
